package com.gamota.mobi;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Shader.TileMode;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AutoCompleteTextView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.androidquery.AQuery;
import com.appota.asdk.topup.TopupAPI;
import com.devspark.appmsg.AppMsg;
import com.gamota.mobi.adapter.AggregateListAdapter;
import com.gamota.mobi.adapter.AggregateListAdapter.RowType;
import com.gamota.mobi.adapter.Item;
import com.gamota.mobi.background.BackgroundTasks;
import com.gamota.mobi.db.DatabaseHelper;
import com.gamota.mobi.download.DownloadManager;
import com.gamota.mobi.download.DownloadManager.Request;
import com.gamota.mobi.download.DownloadService;
import com.gamota.mobi.event.Event;
import com.gamota.mobi.event.Event.BuyFailEvent;
import com.gamota.mobi.event.Event.BuySuccessEvent;
import com.gamota.mobi.event.Event.GetDownloadLinkFailEvent;
import com.gamota.mobi.event.Event.GetDownloadLinkSuccess;
import com.gamota.mobi.event.Event.GetVersionListSuccessEvent;
import com.gamota.mobi.event.Event.HasGiftBox;
import com.gamota.mobi.event.Event.OutOfGiftBox;
import com.gamota.mobi.event.Event.SearchAllCompleteEvent;
import com.gamota.mobi.event.Event.SearchCompleteEvent;
import com.gamota.mobi.event.Event.SearchFailEvent;
import com.gamota.mobi.event.Event.UserInfoSuccessEvent;
import com.gamota.mobi.event.Event.VersionBoughtEvent;
import com.gamota.mobi.event.Event.VersionNotBoughtEvent;
import com.gamota.mobi.model.ContentItemInfo;
import com.gamota.mobi.model.DownloadLaterItem;
import com.gamota.mobi.model.DownloadLink;
import com.gamota.mobi.model.GiftSetting;
import com.gamota.mobi.model.SearchHeader;
import com.gamota.mobi.model.SearchHeader.OnViewAllClickListener;
import com.gamota.mobi.model.SearchItem;
import com.gamota.mobi.model.SearchItem.OnPopupMenuClick;
import com.gamota.mobi.network.InstallBackgroundTask;
import com.gamota.mobi.network.ProgressDialogManager;
import com.gamota.mobi.util.Constants;
import com.gamota.mobi.util.StorageUtils;
import com.gamota.mobi.util.Utils;
import com.gamota.mobi.view.AlertDialogManager;
import com.gamota.mobi.view.LoadMoreListView;
import com.gamota.mobi.view.LoadMoreListView.OnLoadMoreListener;
import com.google.analytics.tracking.android.EasyTracker;

import de.greenrobot.event.EventBus;

public class SearchResultActivity extends SherlockActivity implements OnItemClickListener, OnPopupMenuClick, OnViewAllClickListener, OnClickListener, OnItemSelectedListener, OnLoadMoreListener {
	
	private String searchQuery;
	private String searchType;
	private AQuery aq;
	private AggregateListAdapter aggregateAdapter;
	private List<Item> list;
	private LoadMoreListView listView;
	private BackgroundTasks bgTask;
	private String accessToken;
	private int START = 0;
	private ProgressDialog pDialog;
	private DownloadManager downloadManager;
	private SearchItem selectedItem;
	private String store;
	private int storeId = 2;
	private Spinner spinner;
	private boolean isFirstInit = true;
	private boolean isWatchMovie = false;
	private String versionName = "";
	private int greenTym = -1;
	private int purpleTym = -1;
	private PackageEventReceiver receiver;
	private DialogInterface.OnClickListener onClick;
	private int versionId = 0;
	private String countryCode;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		aq = new AQuery(this);
		searchType = getIntent().getStringExtra(Constants.STORE_KEY);
//		if(searchType.equalsIgnoreCase("books")){
			setTheme(R.style.Theme_Styled_Home);
			setThemeLowEndDevice(R.drawable.action_bar_home);
			aq.id(R.id.line).backgroundColor(getResources().getColor(R.color.ebook_indicator));
//		} else if(searchType.equalsIgnoreCase("comics")){
//			setTheme(R.style.Theme_Styled_Comic);
//			setThemeLowEndDevice(R.drawable.action_bar_comic);
//			aq.id(R.id.line).backgroundColor(getResources().getColor(R.color.comic_indicator));
//		} else if(searchType.equalsIgnoreCase("movies")){
//			setTheme(R.style.Theme_Styled_Movie);
//			setThemeLowEndDevice(R.drawable.action_bar_movie);
//			aq.id(R.id.line).backgroundColor(getResources().getColor(R.color.film_indicator));
//		} else {
//			setTheme(R.style.Theme_Styled_Apps);
//			setThemeLowEndDevice(R.drawable.action_bar_apps);
//			aq.id(R.id.line).backgroundColor(getResources().getColor(R.color.app_indicator));
//		}
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search_result);
		searchQuery = getIntent().getStringExtra(Constants.SEARCH_QUERY);
		getSupportActionBar().setTitle(searchQuery);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		listView = (LoadMoreListView) findViewById(R.id.search_list);
		spinner = (Spinner) findViewById(R.id.spn_search);
		spinner.setOnItemSelectedListener(this);
		bgTask = new BackgroundTasks(this);
		downloadManager = new DownloadManager(getContentResolver(), getPackageName());
	    downloadManager.setAccessAllDownloads(false);
		startDownloadService();
		countryCode = Utils.getStaticCountryCode(this);
		receiver = new PackageEventReceiver();
		IntentFilter filter = new IntentFilter();
		filter.addAction(Intent.ACTION_PACKAGE_ADDED);
		filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
		filter.addDataScheme("package");
		registerReceiver(receiver, filter);
		getUserInfo();
		
		list = new ArrayList<Item>();
		aggregateAdapter = new AggregateListAdapter(this, list);
		aq.id(listView).adapter(aggregateAdapter).itemClicked(this);
		if(searchType.equalsIgnoreCase("apps") || searchType.equalsIgnoreCase("games")){
			spinner.setSelection(1);
		} else if(searchType.equalsIgnoreCase("books")){
			spinner.setSelection(2);
		} else if(searchType.equalsIgnoreCase("comics")){
			spinner.setSelection(3);
		} else if(searchType.equalsIgnoreCase("movies")){
			spinner.setSelection(4);
		} else {
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.search(accessToken, 2, searchQuery, START);
			listView.setOnLoadMoreListener(null);
		}
		EasyTracker.getInstance().setContext(this);
		EasyTracker.getTracker().sendView("Search Screen");
	}
	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
	}
	private void getUserInfo(){
		String accessToken = Utils.getStaticAccessToken(this);
		if(accessToken!="3de71f9e84a325bbfb86466c15b40b1e"){
			bgTask.getUserInfo(accessToken);
		}
	}
	
	public void onEventMainThread(UserInfoSuccessEvent event){
		greenTym = event.getUser().getGreenTym();
		purpleTym = event.getUser().getPurpleTym();
	}
	
	private void setThemeLowEndDevice(int drawableId){
		if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
            BitmapDrawable bg = (BitmapDrawable)getResources().getDrawable(drawableId);
            bg.setTileModeX(TileMode.REPEAT);
            getSupportActionBar().setBackgroundDrawable(bg);
        }
	}
	
	private void startDownloadService() {
		Intent intent = new Intent();
		intent.setClass(this, DownloadService.class);
		startService(intent);
	}
	
	@Override
	public void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		EventBus.getDefault().unregister(this);
	}

	@Override
	public void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		EventBus.getDefault().register(this);
		com.facebook.AppEventsLogger.activateApp(this, getResources().getString(R.string.fb_app_id));
	}
	
	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		unregisterReceiver(receiver);
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		getSupportMenuInflater().inflate(R.menu.activity_search_result, menu);
		View v = (View) menu.findItem(R.id.search).getActionView();
    	final AutoCompleteTextView txtSearch = (AutoCompleteTextView) v.findViewById(R.id.text_search);
    	txtSearch.setOnEditorActionListener(new OnEditorActionListener() {
			
			@Override
			public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
				if (actionId == EditorInfo.IME_ACTION_SEARCH) {
		        	if(!TextUtils.isEmpty(aq.id(R.id.text_search).getText().toString())){
		        		EditText keySearch=aq.id(R.id.text_search).getEditText();
		        		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(keySearch.getWindowToken(), 0);
		        		startSearch();
//		        		txtSearch.setText("");
		        		txtSearch.clearFocus();
			            return true;
		        	} else {
		        		Toast.makeText(SearchResultActivity.this, R.string.input_search, Toast.LENGTH_SHORT).show();
		        		return true;
		        	}
		        }
		        return false;
			}
		});
    	ImageButton btn_search=(ImageButton)v.findViewById(R.id.btn_search);
    	btn_search.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
		        	if(!TextUtils.isEmpty(aq.id(R.id.text_search).getText().toString())){
		        		EditText keySearch=aq.id(R.id.text_search).getEditText();
		        		InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(keySearch.getWindowToken(), 0);
		        		startSearch();
		        		txtSearch.clearFocus();
//		        		txtSearch.setText("");
		        	} else {
		        		Toast.makeText(SearchResultActivity.this, R.string.input_search, Toast.LENGTH_SHORT).show();
		        	}
			}
		});
		return true;
	}

	private void startSearch() {
		getSupportActionBar().setTitle(getString(R.string.search));
		storeId = 2;
		searchType = "all";
		aggregateAdapter.clear();
		isFirstInit = false;
		listView.setOnLoadMoreListener(null);
		aq.id(R.id.progress_search).visible();
		aq.id(R.id.btn_retry_search).gone();
		aq.id(R.id.empty_view).gone();
		aq.id(listView).gone();
//			bgTask.searchAll(accessToken, 2, searchQuery, 0);
		bgTask.search(accessToken, 2,aq.id(R.id.text_search).getText().toString(), 0);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getItemId()) {
		case android.R.id.home:
			finish();
			return true;
		case R.id.menu_search:
			Intent search = new Intent(this, SearchActivity.class);
			search.putExtra(Constants.SEARCH_TYPE, searchType);
			startActivity(search);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void onEventMainThread(SearchAllCompleteEvent event){
		Log.e("SearchAllCompleteEvent","SearchAllCompleteEvent");
		int storeId = event.getStoreId();
		SearchItem item;
		switch (storeId) {
		case 2:
			int max = 0;
			if(event.getItemList().size() >= 3){
				max = 3; 
			} else {
				max = event.getItemList().size();
			}
			if(event.getItemList().size() > 0){
				SearchHeader header = new SearchHeader(this);
				header.setName(getResources().getString(R.string.store_app));
				header.setButtonColor(R.drawable.btn_green_selector);
				header.setNumber(event.getTotalResult());
				header.setListener(this);
				header.setType("apps");
				list.add(header);
				ContentItemInfo i;
				for(int j = 0; j < max; j++){
					i = event.getItemList().get(j);
					item = new SearchItem(this);
					item.setApplicationId(i.getApplicationId());
					item.setInstalled(i.isInstalled());
					item.setApplicationType("android");
					item.setAppstorevnId(i.getAppstorevnId());
					item.setAuthor(i.getAuthor());
					item.setAvatar(i.getAvatar());
					item.setBought(i.getBought());
					item.setIdentifierBundle(i.getPackageName());
					item.setGiftbox(i.getGiftbox());
					item.setDaysToGet(i.getGiftboxDaysToGet());
					item.setInstallAttachApplication(i.getInstallAttachApplication());
					item.setAttachApplicationAvatar(i.getAttachApplicationAvatar());
					item.setAttachApplicationSlug(i.getAttachApplicationSlug());
					item.setAttachApplicationTitle(i.getAttachApplicationTitle());
					item.setPrice(i.getPrice());
					item.setPrice2(i.getPrice2());
					if(i.getTotalRate() > 0){
						item.setRating(i.getSumRate() / i.getTotalRate());
					} else {
						item.setRating(0);
					}
					item.setTitle(i.getTitle());
					item.setStore("apps");
					item.setOnPopupMenuClick(this);
					list.add(item);
				}
			}
//			bgTask.searchAll(accessToken, 4, searchQuery, START);
			aggregateAdapter.notifyDataSetChanged();
			if(list.size() == 0){
				aq.id(R.id.progress_search).gone();
				aq.id(R.id.btn_retry_search).gone();
				aq.id(R.id.empty_view).visible();
				aq.id(listView).gone();
			}
			break;
		case 4:
			if(event.getItemList().size() >= 3){
				max = 3; 
			} else {
				max = event.getItemList().size();
			}
			if(event.getItemList().size() > 0){
				SearchHeader header = new SearchHeader(this);
				header.setName(getResources().getString(R.string.store_ebook));
				header.setButtonColor(R.drawable.btn_orange_selector);
				header.setNumber(event.getTotalResult());
				header.setListener(this);
				header.setType("books");
				list.add(header);
				ContentItemInfo i;
				for(int j = 0; j < max; j++){
					i = event.getItemList().get(j);
					item = new SearchItem(this);
					item.setApplicationId(i.getApplicationId());
					item.setApplicationType("ebook");
					item.setAppstorevnId(i.getAppstorevnId());
					item.setAuthor(i.getAuthor());
					item.setAvatar(i.getAvatar());
					item.setBought(i.getBought());
					item.setGiftbox(i.getGiftbox());
					item.setDaysToGet(i.getGiftboxDaysToGet());
					item.setIdentifierBundle(i.getPackageName());
					item.setPrice(i.getPrice());
					item.setPrice2(i.getPrice2());
					if(i.getTotalRate() > 0){
						item.setRating(i.getSumRate() / i.getTotalRate());
					} else {
						item.setRating(0);
					}
					item.setTitle(i.getTitle());
					item.setStore("books");
					item.setOnPopupMenuClick(this);
					list.add(item);
				}
			}
			bgTask.searchAll(accessToken, 5, searchQuery, START);
			break;
		case 5:
			if(event.getItemList().size() >= 3){
				max = 3; 
			} else {
				max = event.getItemList().size();
			}
			if(event.getItemList().size() > 0){
				SearchHeader header = new SearchHeader(this);
				header.setName(getResources().getString(R.string.store_comic));
				header.setButtonColor(R.drawable.btn_blue_selector);
				header.setNumber(event.getTotalResult());
				header.setListener(this);
				header.setType("comics");
				list.add(header);
				ContentItemInfo i;
				for(int j = 0; j < max; j++){
					i = event.getItemList().get(j);
					item = new SearchItem(this);
					item.setApplicationId(i.getApplicationId());
					item.setApplicationType("comic");
					item.setAppstorevnId(i.getAppstorevnId());
					item.setAuthor(i.getAuthor());
					item.setAvatar(i.getAvatar());
					item.setBought(i.getBought());
					item.setGiftbox(i.getGiftbox());
					item.setDaysToGet(i.getGiftboxDaysToGet());
					item.setIdentifierBundle(i.getPackageName());
					item.setPrice(i.getPrice());
					item.setPrice2(i.getPrice2());
					if(i.getTotalRate() > 0){
						item.setRating(i.getSumRate() / i.getTotalRate());
					} else {
						item.setRating(0);
					}
					item.setTitle(i.getTitle());
					item.setStore("comics");
					item.setOnPopupMenuClick(this);
					list.add(item);
				}
			}
			bgTask.searchAll(accessToken, 6, searchQuery, START);
			break;
		case 6:
				if(event.getItemList().size() >= 3){
					max = 3; 
				} else {
					max = event.getItemList().size();
				}
				aq.id(R.id.progress_search).gone();
				aq.id(R.id.btn_retry_search).gone();
				aq.id(R.id.empty_view).gone();
				aq.id(listView).visible();
				if(event.getItemList().size() > 0){
					SearchHeader header = new SearchHeader(this);
					header.setName(getResources().getString(R.string.store_film));
					header.setButtonColor(R.drawable.btn_red_selector);
					header.setNumber(event.getTotalResult());
					header.setListener(this);
					header.setType("movies");
					list.add(header);
					ContentItemInfo i;
					for(int j = 0; j < max; j++){
						i = event.getItemList().get(j);
						item = new SearchItem(this);
						item.setApplicationId(i.getApplicationId());
						item.setApplicationType("film");
						item.setAppstorevnId(i.getAppstorevnId());
						item.setAuthor(i.getAuthor());
						item.setAvatar(i.getAvatar());
						item.setBought(i.getBought());
						item.setIdentifierBundle(i.getPackageName());
						item.setPrice(i.getPrice());
						item.setGiftbox(i.getGiftbox());
						item.setDaysToGet(i.getGiftboxDaysToGet());
						item.setPrice2(i.getPrice2());
						if(i.getTotalRate() > 0){
							item.setRating(i.getSumRate() / i.getTotalRate());
						} else {
							item.setRating(0);
						}
						item.setTitle(i.getTitle());
						item.setStore("movies");
						item.setOnPopupMenuClick(this);
						list.add(item);
					}
				}
				aggregateAdapter.notifyDataSetChanged();
				if(list.size() == 0){
					aq.id(R.id.progress_search).gone();
					aq.id(R.id.btn_retry_search).gone();
					aq.id(R.id.empty_view).visible();
					aq.id(listView).gone();
				}
			break;
		}
	}
	
	public void onEventMainThread(Event.SearchAllFailEvent e){
		int storeId = e.getStoreId();
		switch (storeId) {
		case 2:
			bgTask.searchAll(accessToken, 4, searchQuery, START);
			break;
		case 4:
			bgTask.searchAll(accessToken, 5, searchQuery, START);
			break;
		case 5:
			bgTask.searchAll(accessToken, 6, searchQuery, START);
			break;
		case 6:
			aq.id(R.id.progress_search).gone();
			aq.id(R.id.btn_retry_search).visible().clicked(this);
			aq.id(R.id.empty_view).gone();
			aq.id(listView).gone();
			break;
		}
	}
	
	public void onEventMainThread(SearchCompleteEvent event){
		SearchItem item;
		int storeId = event.getStoreId();
		if(event.getItemList().size() > 0){
			aq.id(R.id.progress_search).gone();
			aq.id(R.id.btn_retry_search).gone();
			aq.id(R.id.empty_view).gone();
			aq.id(listView).visible();
			listView.setOnLoadMoreListener(this);
			for(ContentItemInfo i : event.getItemList()){
				item = new SearchItem(this);
				item.setApplicationId(i.getApplicationId());
				item.setInstalled(i.isInstalled());
				if(storeId == 2){
					item.setApplicationType("android");
					item.setStore("apps");
					item.setInstallAttachApplication(i.getInstallAttachApplication());
					item.setAttachApplicationAvatar(i.getAttachApplicationAvatar());
					item.setAttachApplicationSlug(i.getAttachApplicationSlug());
					item.setAttachApplicationTitle(i.getAttachApplicationTitle());
				} else if(storeId == 4){
					item.setApplicationType("ebook");
					item.setStore("books");
				} else if(storeId == 5){
					item.setApplicationType("comic");
					item.setStore("comics");
				} else if(storeId == 6){
					item.setApplicationType("film");
					item.setStore("movies");
				}
				item.setAppstorevnId(i.getAppstorevnId());
				item.setAuthor(i.getAuthor());
				item.setAvatar(i.getAvatar());
				item.setBought(i.getBought());
				item.setIdentifierBundle(i.getPackageName());
				item.setPrice(i.getPrice());
				item.setGiftbox(i.getGiftbox());
				item.setDaysToGet(i.getGiftboxDaysToGet());
				item.setPrice2(i.getPrice2());
				if(i.getTotalRate() > 0){
					item.setRating(i.getSumRate() / i.getTotalRate());
				} else {
					item.setRating(0);
				}
				item.setTitle(i.getTitle());
				item.setOnPopupMenuClick(this);
				list.add(item);
			}
			aggregateAdapter.notifyDataSetChanged();
			listView.onLoadMoreComplete();
		} else {
			if(START == 0){
				aq.id(R.id.progress_search).gone();
				aq.id(R.id.btn_retry_search).gone();
				aq.id(R.id.empty_view).visible();
				aq.id(listView).gone();
			} else {
				listView.onLoadMoreComplete();
				listView.setOnLoadMoreListener(null);
			}
		}
	}
	
	public void onEventMainThread(SearchFailEvent e){
		listView.setOnLoadMoreListener(null);
		aq.id(R.id.progress_search).gone();
		aq.id(R.id.btn_retry_search).visible().clicked(this);
		aq.id(R.id.empty_view).gone();
		aq.id(listView).gone();
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View v, int position, long arg3) {
		// TODO Auto-generated method stub
		SearchItem clickedItem = (SearchItem) parent.getItemAtPosition(position);
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.VIEW_EVENT_ACTION, clickedItem.getTitle(), Long.valueOf(1));
		Intent intent = new Intent(this, ItemBrokerActivity.class);
		intent.putExtra(Constants.PREVIOUS_SCREEN, "search");
		intent.putExtra(Constants.SLUG, clickedItem.getApplicationId());
		intent.putExtra(Constants.KEY_REFERER, "direct");
		intent.putExtra(Constants.STORE_KEY, clickedItem.getStore());
		startActivity(intent);
	}
	
	private boolean checkLogin(){
		return Utils.getStaticIsLogin(this);
	}
	
	private void download(final SearchItem item, final int isBought){
		AlertDialogManager am = new AlertDialogManager(this);
		am.showWebViewDialog(aq, item.getInstallAttachApplication(), this, item.getPermission(), R.string.app_permissions, item.getAttachApplicationAvatar(), item.getAttachApplicationTitle(), new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				pDialog = ProgressDialogManager.showProgressDialog(SearchResultActivity.this, R.string.loading);
//				if(item.getPrice() != 0){
//					validAndBuy(item.getPrice(), "green", item, 0, isBought);
//				} else if(item.getPrice2() != 0){
//					validAndBuy(item.getPrice2(), "purple", item, 0, isBought);
//				} else {
					validAndBuy(0, "free", item, 0, 0);
//				}
				dialog.dismiss();
			}
		});
	}

	@Override
	public void onInstallClicked(String store, final SearchItem item) {
		// TODO Auto-generated method stub
		EasyTracker.getTracker().sendEvent(Constants.DOWNLOAD_EVENT_CATEGORY, Constants.LIST_DOWNLOAD_ACTION, item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
		this.store = store;
		this.selectedItem = item;
		isWatchMovie = false;
		if(!countryCode.equalsIgnoreCase("vn")){
			Intent gp = new Intent(Intent.ACTION_VIEW);
			gp.setData(Uri.parse(item.getRootLink()));
			startActivity(gp);
		} else {
			if(true){//checkLogin()
				checkGift();
			} else {
				AlertDialogManager am = new AlertDialogManager(this);
				am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
//							Intent intent = new Intent(SearchResultActivity.this, LoginActivity.class);
//							intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//							startActivity(intent);
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							dialog.dismiss();
							break;
						}
					}
				});
			}
		}
	}

	@Override
	public void onLaunchClicked(String packageName) {
		// TODO Auto-generated method stub
		Intent launch = getPackageManager().getLaunchIntentForPackage(packageName);
		launch.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(launch);
	}

	@Override
	public void onAddToWishListClicked(String store, SearchItem item) {
		// TODO Auto-generated method stub
		this.store = store;
		String addType = null;
		if(store.equalsIgnoreCase("home") || store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games")){
			addType = Constants.ANDROID_STORE;
		} else if(store.equalsIgnoreCase("books")){
			addType = "ebook";
		} else if(store.equalsIgnoreCase("comics")){
			addType = "comic";
		} else {
			addType = "film";
		}
		DatabaseHelper db = new DatabaseHelper(this);
		DownloadLaterItem dlItem = new DownloadLaterItem(item.getAvatar(), item.getTitle(), item.getAuthor(), item.getApplicationId());
		dlItem.setPrice1(item.getPrice());
		dlItem.setPrice2(item.getPrice2());
		dlItem.setPackageName(item.getIdentifierBundle());
		dlItem.setType(addType);
		boolean added = db.addDownloadLater(dlItem);
		if(added){
			Toast.makeText(this, String.format(getResources().getString(R.string.saved), item.getTitle()), Toast.LENGTH_SHORT).show();
		} else {
			Toast.makeText(this, String.format(getResources().getString(R.string.item_exist), item.getTitle()), Toast.LENGTH_SHORT).show();
		}
	}

	@Override
	public void onDownloadClicked(String store, SearchItem item) {
		// TODO Auto-generated method stub
		EasyTracker.getTracker().sendEvent(Constants.EVENT, Constants.LIST_DOWNLOAD_ACTION, item.getTitle() + " in " + item.getApplicationType() + " store", Long.valueOf(1));
		isWatchMovie = false;
		selectedItem = item;
		this.store = store;
		if(checkLogin()){
			pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.getVersionList(accessToken, item.getApplicationId(), "");
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
//						Intent intent = new Intent(SearchResultActivity.this, LoginActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						startActivity(intent);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			});
		}
	}

	@Override
	public void onWatchClicked(SearchItem item) {
		// TODO Auto-generated method stub
		store = "movies";
		if(checkLogin()){
			isWatchMovie = true;
			selectedItem = item;
			pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.getVersionList(accessToken, item.getApplicationId(), "");
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showButtonsDialog(R.string.must_login, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					switch (which) {
					case DialogInterface.BUTTON_POSITIVE:
//						Intent intent = new Intent(SearchResultActivity.this, LoginActivity.class);
//						intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//						startActivity(intent);
						break;
					case DialogInterface.BUTTON_NEGATIVE:
						dialog.dismiss();
						break;
					}
				}
			});
		}
	}
	
	public void onEventMainThread(GetVersionListSuccessEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		if(event.getVersionList().size() == 1){
			if(store.equalsIgnoreCase("books") || store.equalsIgnoreCase("comics")){
				pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
				if(selectedItem.getPrice() != 0){
					validAndBuy(selectedItem.getPrice(), "green", selectedItem, 0, selectedItem.getBought());
				} else if(selectedItem.getPrice2() != 0){
					validAndBuy(selectedItem.getPrice2(), "purple", selectedItem, 0, selectedItem.getBought());
				} else {
					validAndBuy(0, "free", selectedItem, 0, selectedItem.getBought());
				}
			} else {
				pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
				accessToken = Utils.getStaticAccessToken(this);
				versionId = event.getVersionList().get(0).getId();
				bgTask.watchMovie("", accessToken, selectedItem.getApplicationId(), versionId, Utils.getStaticIsRooted(this), "direct");
			}
		} else {
			PopupMenu popupMenu = new PopupMenu(this);
			popupMenu.setHeaderTitle(getResources().getString(R.string.choose_episode));
			String versionName;
			int versionId;
			int price1;
			int price2;
			for (int i = event.getVersionList().size()-1; i >= 0; i--) {
				versionId = event.getVersionList().get(i).getId();
				versionName = event.getVersionList().get(i).getName();
				price1 = event.getVersionList().get(i).getPrice1();
				price2 = event.getVersionList().get(i).getPrice2();
				popupMenu.add(versionId, versionName, "", price1, price2, true).setIcon(getResources().getDrawable(R.drawable.ic_arrow_down));
			}  
			popupMenu.setOnItemSelectedListener(new main.java.com.u1aryz.android.lib.newpopupmenu.PopupMenu.OnItemSelectedListener() {
				@Override
				public void onItemSelected(final main.java.com.u1aryz.android.lib.newpopupmenu.MenuItem menuItem) {
					// TODO Auto-generated method stub
					SearchResultActivity.this.versionName = menuItem.getTitle();
					SearchResultActivity.this.versionId = menuItem.getItemId();
					accessToken = Utils.getStaticAccessToken(SearchResultActivity.this);
					if(store.equalsIgnoreCase("books") || store.equalsIgnoreCase("comics")){
//						if(menuItem.getPrice1() != 0){
//							validAndBuy(menuItem.getPrice1(), "green", selectedItem, menuItem.getItemId());
//						} else if(menuItem.getPrice2() != 0){
//							validAndBuy(menuItem.getPrice2(), "purple", selectedItem, menuItem.getItemId());
//						} else {
//							pDialog = ProgressDialogManager.showProgressDialog(SearchResultActivity.this, R.string.loading);
//							validAndBuy(0, "free", selectedItem, menuItem.getItemId());
//						}
						bgTask.checkVersionBought("", accessToken, null, menuItem);
					} else {
						pDialog = ProgressDialogManager.showProgressDialog(SearchResultActivity.this, R.string.loading);
						bgTask.watchMovie("", accessToken, selectedItem.getApplicationId(), menuItem.getItemId(), Utils.getStaticIsRooted(SearchResultActivity.this), "direct");
					}
				}
			});
			popupMenu.show();
		}
	}
	
	public void onEventMainThread(VersionBoughtEvent e){
		if(e.getItem().getPrice1() != 0){
			validAndBuy(e.getItem().getPrice1(), "green", selectedItem, e.getItem().getItemId(), 1);
		} else if(e.getItem().getPrice2() != 0){
			validAndBuy(e.getItem().getPrice2(), "purple", selectedItem, e.getItem().getItemId(), 1);
		} else {
			pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			validAndBuy(0, "free", selectedItem, e.getItem().getItemId(), 1);
		}
	}
	
	public void onEventMainThread(VersionNotBoughtEvent e){
		if(e.getItem().getPrice1() != 0){
			validAndBuy(e.getItem().getPrice1(), "green", selectedItem, e.getItem().getItemId(), 0);
		} else if(e.getItem().getPrice2() != 0){
			validAndBuy(e.getItem().getPrice2(), "purple", selectedItem, e.getItem().getItemId(), 0);
		} else {
			pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			validAndBuy(0, "free", selectedItem, e.getItem().getItemId(), 0);
		}
	}
	
	public void onEventMainThread(BuySuccessEvent event){
		String accessToken = Utils.getStaticAccessToken(this);
		bgTask.getDownloadLink("",accessToken, event.getSlug(), event.getVersionId(), Utils.getStaticIsRooted(this), "direct");
	}

	public void onEventMainThread(BuyFailEvent event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, event.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}
	
	private void checkGift(){
		if(selectedItem.getGiftbox() == 1){
			bgTask.checkRemainGift(accessToken, selectedItem.getApplicationId());
		} else {
			download(selectedItem, 0);
		}
	}
	
	public void onEventMainThread(HasGiftBox e){
		AlertDialogManager am = new AlertDialogManager(this);
		final DatabaseHelper db = new DatabaseHelper(this);
		GiftSetting gift = db.getGiftSync(selectedItem.getApplicationId());
		if(gift != null && gift.getReceived() == 1){
			download(selectedItem, 1);
		} else {
			if(selectedItem.getDaysToGet() == 0){
				final GiftSetting gs = new GiftSetting();
				gs.setReceived(0);
				gs.setDays(0);
				gs.setName(selectedItem.getIdentifierBundle());
				gs.setSlug(selectedItem.getApplicationId());
				gs.setAppName(selectedItem.getTitle());
				gs.setPicture(selectedItem.getAvatar());
				onClick = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						download(selectedItem, 1);
						db.addGift(gs);
					}
				};
				am.showGiftDialog(R.string.gift_message, 0, onClick);
			} else {
				final GiftSetting gs = new GiftSetting();
				gs.setReceived(0);
				gs.setDays(selectedItem.getDaysToGet());
				gs.setName(selectedItem.getIdentifierBundle());
				gs.setSlug(selectedItem.getApplicationId());
				gs.setAppName(selectedItem.getTitle());
				gs.setPicture(selectedItem.getAvatar());
				gs.setTimeToReceive(Utils.calculateDaysToGetGift(selectedItem.getDaysToGet()));
				onClick = new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						download(selectedItem, 1);
						db.addGift(gs);
					}
				};
				am.showGiftDialog(R.string.gift_message_days, selectedItem.getDaysToGet(), onClick);
			}
		}
	}
	
	public void onEventMainThread(OutOfGiftBox e){
		download(selectedItem, 1);
	}

	public void onEventMainThread(GetDownloadLinkSuccess event){
		if(pDialog != null){
			pDialog.dismiss();
		}
		if(selectedItem.getInstallAttachApplication() == 1){
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.buyAttachedContent(accessToken, selectedItem.getAttachApplicationSlug(), 0);
		}
		if(isWatchMovie){
//			Intent watch = new Intent(SearchResultActivity.this, VideoActivity.class);
//			watch.putExtra(Constants.MOVIE_URL, event.getDl().getDownload());
//			watch.putExtra(Constants.MOVIE_TITLE, selectedItem.getTitle());
//			watch.putExtra(Constants.MOVIE_EPISODE, versionName);
//			watch.putExtra(Constants.KEY_PRICE_1, selectedItem.getPrice());
//			watch.putExtra(Constants.KEY_PRICE_2, selectedItem.getPrice2());
//			watch.putExtra(Constants.KEY_VERSION, versionId);
//			watch.putExtra(Constants.KEY_SLUG, selectedItem.getApplicationId());
//			watch.putExtra(Constants.IS_MOVIE_PURCHASED, selectedItem.getBought());
//			startActivity(watch);
		} else {
			DownloadLink download = event.getDl();
			List<String> extraUrls = download.getExtraDownloads();
			if(extraUrls.size() > 0){
				for(String extraUrl : extraUrls){
					Uri srcUri = Uri.parse(extraUrl.replace(" ", "%20"));
					DownloadManager.Request request = new Request(srcUri);
					if(extraUrl.endsWith("obb")){
						String obbDir = StorageUtils.OBB_ROOT + selectedItem.getIdentifierBundle() + "/";
						File obb = new File(obbDir);
						if(!obb.exists()){
							obb.mkdirs();
						}
						request.setDestinationUri(Uri.fromFile(new File(obbDir + Utils.getFileName(extraUrl))));	
					} else {
						request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(extraUrl))));
					}
					request.setTitle(String.format(getResources().getString(R.string.additional_file), selectedItem.getTitle()));
					request.setDescription(selectedItem.getAvatar());
					request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
					downloadManager.enqueue(request);
				}
			}
			if(event.getSlug().equalsIgnoreCase(selectedItem.getApplicationId())){
				String url = download.getDownload();
				Uri srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				request.setTitle(selectedItem.getTitle());
				request.setDescription(selectedItem.getAvatar());
				setDownloadData(request, url, store);
				downloadManager.enqueue(request);
			} else {
				String url = download.getDownload();
				Uri srcUri = Uri.parse(url.replace(" ", "%20"));
				DownloadManager.Request request = new Request(srcUri);
				request.setTitle(event.getSlug());
				request.setDescription("");
				setDownloadData(request, url, "apps");
				downloadManager.enqueue(request);
			}
			
		}
	}
	
	public void onEventMainThread(GetDownloadLinkFailEvent e){
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		AppMsg.makeText(this, e.getMessage(), AppMsg.STYLE_ALERT, null).show();
	}

	private void setDownloadData(Request request, String url, String store){
		if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
			request.setMimeType(StorageUtils.APPS_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.APPS_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("books")){
			request.setMimeType(StorageUtils.EBOOK_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.EBOOK_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("comics")){
			request.setMimeType(StorageUtils.COMIC_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.COMIC_ROOT + Utils.getFileName(url))));
		} else if(store.equalsIgnoreCase("movies")){
			request.setMimeType(StorageUtils.MOVIES_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.MOVIES_ROOT + Utils.getFileName(url))));
		} else {
			request.setMimeType(StorageUtils.DATA_ROOT.toLowerCase(Locale.US));
			request.setDestinationUri(Uri.fromFile(new File(StorageUtils.DATA_ROOT + Utils.getFileName(url))));
		}
	}

	@Override
	public void onViewAllClick(String type) {
		// TODO Auto-generated method stub
		Intent i = new Intent(SearchResultActivity.this, ViewAllSearchResultActivity.class);
		i.putExtra(Constants.STORE_KEY, type);
		i.putExtra(Constants.SEARCH_QUERY, searchQuery);
		startActivity(i);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_retry_search:
			aq.id(R.id.progress_search).visible();
			aq.id(R.id.btn_retry_search).gone();
			aq.id(R.id.empty_view).gone();
			aq.id(listView).gone();
//			if(searchType.equalsIgnoreCase("all")){
//				accessToken = Utils.getStaticAccessToken(this);
//				bgTask.searchAll(accessToken, 2, searchQuery, 0);
//			} else if(searchType.equalsIgnoreCase("apps")){
//				accessToken = Utils.getStaticAccessToken(this);
//				bgTask.search(accessToken, 2, searchQuery, 0);
//			} else if(searchType.equalsIgnoreCase("books")){
//				accessToken = Utils.getStaticAccessToken(this);
//				bgTask.search(accessToken, 4, searchQuery, 0);
//			} else if(searchType.equalsIgnoreCase("comics")){
//				accessToken = Utils.getStaticAccessToken(this);
//				bgTask.search(accessToken, 5, searchQuery, 0);
//			} else if(searchType.equalsIgnoreCase("movies")){
//				accessToken = Utils.getStaticAccessToken(this);
//				bgTask.search(accessToken, 6, searchQuery, 0);
//			}
			bgTask.search(accessToken, 2, searchQuery, 0);
			break;
		default:
			break;
		}
	}

	@Override
	public void onItemSelected(AdapterView<?> arg0, View v, int pos, long arg3) {
		// TODO Auto-generated method stub
		Log.e("onItemSelected","onItemSelected search Result activity");
		switch (pos) {
		case 0:
			if(!isFirstInit){
				storeId = 2;
				searchType = "all";
				aggregateAdapter.clear();
				isFirstInit = false;
				listView.setOnLoadMoreListener(null);
				aq.id(R.id.progress_search).visible();
				aq.id(R.id.btn_retry_search).gone();
				aq.id(R.id.empty_view).gone();
				aq.id(listView).gone();
//				bgTask.searchAll(accessToken, 2, searchQuery, 0);
				bgTask.search(accessToken, 2, searchQuery, 0);
			}
			break;
		case 1:
			aq.id(R.id.progress_search).visible();
			aq.id(R.id.btn_retry_search).gone();
			aq.id(R.id.empty_view).gone();
			aq.id(listView).gone();
			listView.setOnLoadMoreListener(this);
			storeId = 2;
			searchType = "apps";
			aggregateAdapter.clear();
			isFirstInit = false;
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.search(accessToken, 2, searchQuery, 0);
			break;
//		case 2:
//			aq.id(R.id.progress_search).visible();
//			aq.id(R.id.btn_retry_search).gone();
//			aq.id(R.id.empty_view).gone();
//			aq.id(listView).gone();
//			listView.setOnLoadMoreListener(this);
//			storeId = 4;
//			searchType = "books";
//			aggregateAdapter.clear();
//			isFirstInit = false;
//			accessToken = Utils.getStaticAccessToken(this);
//			bgTask.search(accessToken, 4, searchQuery, 0);
//			break;
//		case 3:
//			aq.id(R.id.progress_search).visible();
//			aq.id(R.id.btn_retry_search).gone();
//			aq.id(R.id.empty_view).gone();
//			aq.id(listView).gone();
//			listView.setOnLoadMoreListener(this);
//			storeId = 5;
//			searchType = "comics";
//			aggregateAdapter.clear();
//			isFirstInit = false;
//			accessToken = Utils.getStaticAccessToken(this);
//			bgTask.search(accessToken, 5, searchQuery, 0);
//			break;
//		case 4:
//			aq.id(R.id.progress_search).visible();
//			aq.id(R.id.btn_retry_search).gone();
//			aq.id(R.id.empty_view).gone();
//			aq.id(listView).gone();
//			listView.setOnLoadMoreListener(this);
//			storeId = 6;
//			searchType = "movies";
//			aggregateAdapter.clear();
//			isFirstInit = false;
//			accessToken = Utils.getStaticAccessToken(this);
//			bgTask.search(accessToken, 6, searchQuery, 0);
//			break;
		default:
			aq.id(R.id.progress_search).visible();
			aq.id(R.id.btn_retry_search).gone();
			aq.id(R.id.empty_view).gone();
			aq.id(listView).gone();
			listView.setOnLoadMoreListener(this);
			storeId = 2;
			searchType = "apps";
			aggregateAdapter.clear();
			isFirstInit = false;
			accessToken = Utils.getStaticAccessToken(this);
			bgTask.search(accessToken, 2, searchQuery, 0);
			break;
		}
	}

	@Override
	public void onNothingSelected(AdapterView<?> arg0) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		START = START + 20;
		bgTask.search(accessToken, storeId, searchQuery, START);
	}
	
	private void validAndBuy(int price, String tymType, SearchItem item, int versionId, int isBought){
		if(isBought == 1){
			if(pDialog == null){
				pDialog = ProgressDialogManager.showProgressDialog(this, R.string.loading);
			}
			bgTask.buyContent("",Utils.getStaticAccessToken(this), item.getApplicationId(), versionId);
		} else {
			if(tymType.equals("green")){
				if(greenTym < price && greenTym != -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(SearchResultActivity.this, PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(SearchResultActivity.this).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(greenTym == -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
//					Intent intent = new Intent(SearchResultActivity.this, ConfirmBuyActivity.class);
//					Bundle bundle = new Bundle();
//					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
//					bundle.putString(Constants.KEY_NAME, item.getTitle());
//					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
//					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
//					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
//					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
//					bundle.putString(Constants.KEY_EP, versionName);
//					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
//					intent.putExtras(bundle);
//					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("purple")){
				if(purpleTym < price && purpleTym != -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showButtonsDialog(R.string.lack_of_tym, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							// TODO Auto-generated method stub
							switch (which) {
							case DialogInterface.BUTTON_POSITIVE:
//								Intent intent = new Intent(SearchResultActivity.this, PaymentActivity.class);
//								Bundle bundle = new Bundle();
//								bundle.putInt(AccountActivity.KEY_GREEN_TYM, greenTym);
//								bundle.putInt(AccountActivity.KEY_PURPLE_TYM, purpleTym);
//								intent.putExtras(bundle);
//								startActivity(intent);
								List<String> scopes = new ArrayList<String>();
								scopes.add("user.info");
								scopes.add("user.email");
								TopupAPI.getInstance().setContext(SearchResultActivity.this).topupTYM(scopes, "");
								break;
							case DialogInterface.BUTTON_NEGATIVE:
								dialog.dismiss();
								break;
							}
						}
					});
				} else if(purpleTym == -1){
					AlertDialogManager am = new AlertDialogManager(this);
					am.showPositiveDialog(R.string.cannot_buy_thistime, android.R.string.ok, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
						}
					});
				} else {
//					Intent intent = new Intent(SearchResultActivity.this, ConfirmBuyActivity.class);
//					Bundle bundle = new Bundle();
//					bundle.putString(Constants.KEY_IMAGE, item.getAvatar());
//					bundle.putString(Constants.KEY_NAME, item.getTitle());
//					bundle.putString(Constants.KEY_AUTHOR, item.getAuthor());
//					bundle.putInt(Constants.KEY_PRICE_1, item.getPrice());
//					bundle.putInt(Constants.KEY_PRICE_2, item.getPrice2());
//					bundle.putLong(Constants.KEY_VERSION, Long.valueOf(versionId));
//					bundle.putString(Constants.KEY_EP, versionName);
//					bundle.putString(Constants.KEY_SLUG, item.getApplicationId());
//					intent.putExtras(bundle);
//					startActivityForResult(intent, 0);
				}
			} else if(tymType.equals("free")){
				bgTask.getDownloadLink("",accessToken, item.getApplicationId(), versionId, Utils.getStaticIsRooted(this), "direct");
//				bgTask.buyContent("",Utils.getStaticAccessToken(this), item.getApplicationId(), versionId);
			}
		}
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, intent);
		if(pDialog != null && pDialog.isShowing()){
			pDialog.dismiss();
		}
		if(requestCode == 0 && resultCode == Activity.RESULT_OK){
			AppMsg.makeText(this, R.string.buy_success, AppMsg.STYLE_INFO, null).show();
			String accessToken = Utils.getStaticAccessToken(this);
			bgTask.getDownloadLink("",accessToken, intent.getExtras().getString(Constants.SLUG), intent.getExtras().getLong(Constants.KEY_VERSION), Utils.getStaticIsRooted(this), "direct");
		}
	}

	private class PackageEventReceiver extends BroadcastReceiver {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String action = intent.getAction();
			if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_ADDED)) {
				String installedName = intent.getDataString().split(":")[1];
				String packageName = "";
				SearchItem item;
				for(int i = 0; i < list.size(); i++){
					if(list.get(i).getViewType() == RowType.LIST_ITEM.ordinal()){
						item = (SearchItem) list.get(i);
						packageName = item.getIdentifierBundle();
						if(packageName == null || !packageName.contains(".")){
							continue;
						}
						if(packageName.equalsIgnoreCase(installedName)){
							item.setInstalled(true);
						}
					}
				}
				aggregateAdapter.notifyDataSetChanged();
			} else if (action.equalsIgnoreCase(Intent.ACTION_PACKAGE_REMOVED)) {
				String packageName = "";
				SearchItem item;
				String uninstalledName = intent.getDataString().split(":")[1];
				for(int i = 0; i < list.size(); i++){
					if(list.get(i).getViewType() == RowType.LIST_ITEM.ordinal()){
						item = (SearchItem) list.get(i);
						packageName = item.getIdentifierBundle();
						if(packageName == null || !packageName.contains(".")){
							continue;
						}
						if(packageName.equalsIgnoreCase(uninstalledName)){
							item.setInstalled(false);
						}
					}
				}
				aggregateAdapter.notifyDataSetChanged();
			}
		}
	}
	
	public void onEventMainThread(final Event.DownloadFailEvent e){
		if(e.getMessage() != null){
			if(e.getMessage().contains("exist")){
				AlertDialogManager am = new AlertDialogManager(this);
				am.showFileDowloadDialog(store, R.string.install_already_exist_file, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						switch (which) {
						case DialogInterface.BUTTON_POSITIVE:
							if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
								boolean autoInstall = PreferenceManager.getDefaultSharedPreferences(SearchResultActivity.this).getBoolean(SettingsActivity.KEY_AUTO_INSTALL, false);
					    		if(!autoInstall){
					    			Utils.installAPK(SearchResultActivity.this, StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
					    		} else {
					    			InstallBackgroundTask task = new InstallBackgroundTask(SearchResultActivity.this);
					    			task.execute(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()), selectedItem.getTitle());
					    		}
							} else if(store.equalsIgnoreCase("books")){
								openEbook(StorageUtils.EBOOK_ROOT + Utils.getFileName(e.getPath()));
							} else if(store.equalsIgnoreCase("comics")){
								openComic(StorageUtils.COMIC_ROOT + Utils.getFileName(e.getPath()));
							} else {
//								Intent watch = new Intent(SearchResultActivity.this, VideoActivity.class);
//								watch.putExtra(Constants.MOVIE_URL, StorageUtils.MOVIES_ROOT + Utils.getFileName(e.getPath()));
//								watch.putExtra(Constants.MOVIE_TITLE, Utils.getFileName(e.getPath()));
//								watch.putExtra(Constants.MOVIE_EPISODE, "");
//								watch.putExtra(Constants.KEY_PRICE_1, 0);
//								watch.putExtra(Constants.KEY_PRICE_2, 0);
//								watch.putExtra(Constants.KEY_VERSION, 0);
//								watch.putExtra(Constants.KEY_SLUG, "");
//								watch.putExtra(Constants.IS_MOVIE_PURCHASED, true);
//								startActivity(watch);
							}
							break;
						case DialogInterface.BUTTON_NEGATIVE:
							if(store.equalsIgnoreCase("apps") || store.equalsIgnoreCase("games") || store.equalsIgnoreCase("home")){
								Utils.deleteFile(StorageUtils.APPS_ROOT + Utils.getFileName(e.getPath()));
							} else if(store.equalsIgnoreCase("books")){
								Utils.deleteFile(StorageUtils.EBOOK_ROOT + Utils.getFileName(e.getPath()));
							} else if(store.equalsIgnoreCase("comics")){
								Utils.deleteFile(StorageUtils.COMIC_ROOT + Utils.getFileName(e.getPath()));
							} else {
								Utils.deleteFile(StorageUtils.MOVIES_ROOT + Utils.getFileName(e.getPath()));
							}
							break;
						case DialogInterface.BUTTON_NEUTRAL:
							dialog.dismiss();
							break;
						}
					}
				});
			} else {
				AppMsg.makeText(this, e.getMessage(), AppMsg.STYLE_ALERT, null).show();
			}
		}
		downloadManager.remove(e.getId());
	}
	
	public void openEbook(String path){
		if(Utils.checkCoolReader(this, path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/epub+zip");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showDialog(R.string.no_ebook_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(SearchResultActivity.this);
					String items[] = {"Cool Reader"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(SearchResultActivity.this);
							bgTask.buyContent("", accessToken, "cooldreader", 0);
						}
					});
				}
			});
		}
	}
	
	private void openComic(String path){
		if(Utils.checkDroidComicViewer(this, path)){
			Intent intent = new Intent(Intent.ACTION_VIEW);
			intent.setDataAndType(Uri.parse(path), "application/x-acv");
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			startActivity(intent);
		} else {
			AlertDialogManager am = new AlertDialogManager(this);
			am.showDialog(R.string.no_comic_reader, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface arg0, int arg1) {
					// TODO Auto-generated method stub
					AlertDialogManager am = new AlertDialogManager(SearchResultActivity.this);
					String items[] = {"Droid Comic Viewer"};
					am.showDialogWithItems(R.string.choose_book_reader_app, items, new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface v, int pos) {
							// TODO Auto-generated method stub
							accessToken = Utils.getStaticAccessToken(SearchResultActivity.this);
							bgTask.buyContent("", accessToken, Utils.ACV_SLUG, 0);
						}
					});
				}
			});
		}
	}
}
